package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.entity.History;
import com.example.service.HistoryService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("historys")
public class HistoryController {

    @Autowired
    private HistoryService historyService;


    /**
     * 搜索历史列表查询
     * @return
     */
    @GetMapping("/getListHistory")
    public R getListHistory(){

        List<History> historyList = historyService.list();
        return R.success("搜索历史列表查询！",historyList);
    }

    /**
     * 添加搜索历史
     * @return
     */
    @PostMapping("/addHistory")
    public R addHistory(@RequestBody History history){

        if (!history.getContent().isEmpty() || history.getContent()!=""){
            boolean save = historyService.save(history);
            if (save){
                return R.success("添加搜索历史成功！",history.getContent());
            }
        }
        return R.error("添加搜索历史失败！");
    }

    /**
     * 通过id查询搜索历史
     * @return
     */
    @GetMapping("/getHistoryById")
    public R getHistoryById(@RequestParam int id) {

        LambdaQueryWrapper<History> lqw =new LambdaQueryWrapper<>();
        lqw.eq(History::getId,id);
        History one = historyService.getOne(lqw);
        return R.success("查询搜索历史",one);
    }

    /**
     * 修改搜索历史
     * @return
     */
    @PutMapping("/updateHistory")
    public R updateHistory(@RequestBody History history){
        boolean b = historyService.updateById(history);
        if (b){
           return R.success("修改搜索历史成功",history);
        }else {
           return R.error("修改搜索历史失败！");
        }
    }

    /**
     * 通过id删除搜索历史
     * @return
     */
    @DeleteMapping("/deleteHistory/{id}")
    public R deleteHistory(@PathVariable int id){

        boolean b = historyService.removeById(id);
        if (b){
           return R.success("删除搜索历史成功",id);
        }else {
           return R.error("删除搜索历史失败！");
        }
    }




    /**
     * 删除所有搜索历史
     * @return
     */
    @GetMapping("/deleteAllHistory")
    public R deleteAllHistory(){

//        boolean b = historyService.removeById(id);
        boolean success = historyService.remove(null);

        if (success){
            return R.success("删除所有搜索历史成功",null);
        }else {
            return R.error("删除所有搜索历史失败！");
        }
    }

}

